package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"strings"
)

type Log struct {
	Name     string
	Password string
}

type testJS struct {
	Code int    `json:"id"`
	Msg  string `json:"content"`
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()       //解析url传递的参数，对于POST则解析响应包的主体（request body）
	fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])
	for k, v := range r.Form {
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到浏览器的
}

func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	r.ParseForm()
	if r.Method == "GET" {
		t, _ := template.ParseFiles("template/login.gtpl")
		t.Execute(w, nil)
	} else {
		information := &Log{r.Form["username"][0], r.Form["Password"][0]}
		t, _ := template.ParseFiles("template/List.gtpl")
		t.Execute(w, information)
		fmt.Println("userName:", r.Form["username"])
		fmt.Println("password:", r.Form["password"])
	}
}

func test(w http.ResponseWriter, r *http.Request) {
	res := &testJS{
		200,
		"验证成功"}
	msg, _ := json.Marshal(res)
	w.Write(msg)
}

func main() {
	http.HandleFunc("/", sayhelloName)
	http.HandleFunc("/js/test", test) //设置访问的路由
	http.HandleFunc("/login", login)  //设置访问的路由
	http.Handle("/file/",
		http.StripPrefix("/file/",
			http.FileServer(http.Dir("file")))) //设置静态文件的路由
	err := http.ListenAndServe(":8888", nil) //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
